import React, { useState, useEffect, useCallback } from 'react';
import ChatWindow from './components/ChatWindow';
import RecipeList from './components/RecipeList';
import { getRecipes } from './services/api';

function App() {
  const [recipes, setRecipes] = useState([]);
  const [error, setError] = useState('');

  const fetchRecipes = useCallback(async () => {
    try {
      const response = await getRecipes();
      const sortedRecipes = response.data.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
      setRecipes(sortedRecipes);
    } catch (err) {
      setError('无法获取食谱。后端服务器是否正在运行？');
      console.error(err);
    }
  }, []);

  useEffect(() => {
    fetchRecipes();
  }, [fetchRecipes]);

  const handleRecipeSaved = () => {
    fetchRecipes();
  };

  const handleRecipeDeleted = (deletedRecipeId) => {
    setRecipes(recipes.filter(recipe => recipe.id !== deletedRecipeId));
  };

  const handleRecipeUpdated = (updatedRecipe) => {
    setRecipes(recipes.map(recipe => recipe.id === updatedRecipe.id ? updatedRecipe : recipe));
  };

  return (
    <div className="app-container">
      <header style={{ textAlign: 'center', marginBottom: '40px' }}>
        <h1>AI 家庭食谱</h1>
        <p>您的个人AI食谱日记。</p>
      </header>
      <main className="main-content">
        <div>
          <ChatWindow onRecipeSaved={handleRecipeSaved} />
        </div>
        <div>
          {error && <p style={{ color: 'red', textAlign: 'center' }}>{error}</p>}
          <RecipeList 
            recipes={recipes} 
            onRecipeDeleted={handleRecipeDeleted}
            onRecipeUpdated={handleRecipeUpdated} 
          />
        </div>
      </main>
    </div>
  );
}

export default App;